package frameWork.mainComponent;

/**
 * 每tick执行一次
 */
public class MainTick {

    Runnable runnable=null;

    private int tick=50;
    /**
     * 默认50，也就是1000/50,每秒20次
     * @param tick 设置间隔毫秒数
     */
    public void setTick(int tick) {
        this.tick = tick*1000000;
    }

    boolean breakAble;
    /**
     * 结束MainTick，推出
     */
    public void dispose(){
        breakAble=true;
    }

    private void runTick(){
        if(runnable!=null){
            runnable.run();
        }
    }

    public MainTick(Runnable runnable){
        this.runnable=runnable;

        Thread thread= new Thread(()->{
            try {
                for (; ; ) {
                    if(breakAble)break;
                    long last = System.nanoTime();
                    runTick();
                    long now = System.nanoTime();
                    long p =tick - (now  -  last) ;
                    //System.out.println(p/1000000.0+" "+(now  -  last)/1000000.0);
                    if (p > 0) Thread.sleep(p/1000000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        thread.start();
    }
}
